#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: ZC
@file: iting
@time: 2020-07-12
"""

#import sys
#sys.path.append(".")

import copy,json,re
import requests as req
from .. import config
from ..api import MusicApi
from ..song import BasicSong
from . import iting_utils as itingu

#import importlib
#importlib.reload(sys)


class ItingApi(MusicApi):
    session = copy.deepcopy(MusicApi.session)
    #session.headers.update(headers)


class ItingSong(BasicSong):
    def __init__(self):
        super(ItingSong, self).__init__()
        self.content_id = ""

def get_songmid(content, keyword, author):
    content = content or {}
    for i in content.get("song_list") or []:
        sname = i.get("songname") or ""
        if type(sname) is not str: sname = sname.decode("utf-8")
        sname = re.sub(u'[^\u4e00-\u9fa5]', "", sname)
        if keyword != sname: continue
        for s in i.get("singer") or []:
            if s and s.get("name") == author:
                return i.get("songmid")

    return None

def get_real_url(url):
    rurl = None

    try:
        itu = itingu.ItingUtils().get_instance()
        code, result = itu.iting_get(url)
        if result and result.get("url"):
            rurl = result.get("url")
    except: pass

    return rurl


def get_downsong(content, keyword):
    suffix = ["FLAC", "24Bit_FLAC"]
    songs = []
    try:
        murl = None
        for i in suffix:
            for k, v in (content.get("url") or {}).items():
                if k == i and v:
                    murl = v
                    break
            if murl: break
        murl = get_real_url(murl)
        if not murl: raise Exception()
        song = ItingSong()
        song.source = "ITING"
        song.id = content.get("id", "")
        song.title = keyword
        song.singer = content.get("singer", "")
        song.album = content.get("album", "") or keyword
        song.cover_url = ""
        song.lyrics_url = ""
        song.content_id = content.get("id", "")
        song.song_url = murl
        ext = "mp3" if song.song_url and song.song_url.find("mp3") >=0 else "flac"
        song.ext = ext
        songs.append(song)
    except: pass

    return songs
            
def iting_search(keyword, author=None) -> list:
    """ 搜索音乐 """
    itu = itingu.ItingUtils().get_instance()
    reqdata = "w={}&p=1&n=20".format(keyword)
    songlist = []
    try:
        code, content = itu.iting_post(data=reqdata)
        songmid = get_songmid(content, keyword, author)
        if not songmid:
            print("songmid can not find")
            raise Exception()
        code, content = itu.iting_post(data="mid=%s" % str(songmid), uri="get_song")
        songlist = get_downsong(content, keyword)
        if not songlist: raise Exception()
    except Exception as e:
        raise Exception("cannot get {} -- {}".format(keyword, author))

    return songlist

search = iting_search
